package global

import (
	"errors"
	"github.com/fsnotify/fsnotify"
	"go_server/game_server/api/service/bag"
	"go_server/game_server/api/service/build"
	"go_server/game_server/api/service/gm"
	"go_server/game_server/protocol/pb"
	"go_server/game_server/util"
	"go_server/game_server/world_manager"
	"go_server/login_server/initializer/config_init"
	"go_server/zinx/ziface"
	"go_server/zinx/zlog"
	"go_server/zinx/zutils"
	"net/http"
)

var (
	serverObj ziface.IServer
	gmMode    bool
)

func init() {
	configViper, fullPathFile := util.CreateConfig("gm")
	configViper.WatchConfig()

	configMD5 := zutils.ReadFileMd5(fullPathFile)
	gmMode = configViper.GetBool("gm_mode")
	configViper.OnConfigChange(func(in fsnotify.Event) {
		changeMd5 := zutils.ReadFileMd5(fullPathFile)
		if changeMd5 == configMD5 {
			return
		}

		configMD5 = changeMd5
		gmMode = configViper.GetBool("gm_mode")
		if gmMode {
			serverObj.AddRouter(uint32(pb.ProtocolManager_GMCommand), gm.GetGmCommandApi())
		} else {
			serverObj.RemoveRouter(uint32(pb.ProtocolManager_GMCommand))
		}

		zlog.Warn("zinx config changed!!!!")
	})
}

func SetGmMode(s ziface.IServer) {
	serverObj = s
	if gmMode {
		serverObj.AddRouter(uint32(pb.ProtocolManager_GMCommand), gm.GetGmCommandApi())
	}
}

func OnRoleLogoutEvent(conn ziface.IConnection) {
	iRoleId, err := conn.GetProperty("roleId")
	if err != nil {
		return
	}
	roleId := iRoleId.(int64)
	if roleId <= 0 {
		return
	}
	conn.RemoveProperty("roleId")

	go build.OnRoleLogoutCallBack(roleId)
	go bag.OnRoleLogoutCallBack(roleId)

	world_manager.WorldMgrObj.RemovePlayerConn(roleId)
}

func ConnectAuthFunc(r *http.Request) error {
	value := r.Header.Get("Authorization")
	if len(value) <= 0 {
		return errors.New("not contains Authorization")
	}

	//uid := r.Header.Get("uid")
	uid := "123456"
	token := "eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJqdGkiOiIiLCJpc3MiOiJsb2dpbiIsImF1ZCI6IiIsInN1YiI6IiIsImlhdCI6MTcyNjY1MTYwMiwibmJmIjowLCJleHAiOjE3MjY3MzgwMDIsInVkIjp7InVpZCI6IjEyMzQ1NiJ9fQ.WgZgZ91vJ2tuSaPMJ06NWQTqxxevub7jiX3-RhnvLM4"

	configViper := config_init.GetConfigViper()
	secret := configViper.GetString("secret")
	_, payload, _ := zutils.VerifyJwt(token, secret)

	zlog.Infof("token解析得到的uid：%v", payload.UserDefined["uid"])

	if value == "Token-Token" || payload.UserDefined["uid"] == uid {
		return nil
	} else {
		return errors.New("Illegal user")
	}
}
